﻿using HtmlAgilityPack;
using Rsd.Dudu;
using Rsd.Dudu.BizModel;
using Rsd.Dudu.Helpers;
using Rsd.Dudu.Web;
using Rsd.Dudu.Web.MVC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml; 

namespace Rsd.Faith.Info.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class InfoController : Rsd.Faith.Core.FaithController
    {
        /// <summary>
        /// 查询小区列表
        /// </summary>
        /// <returns></returns>
        [ApiService("查询小区列表", false)]
        public object GetXiaoQuList()
        {
            var report = MyType.GetReportService<Rsd.Faith.Models.InfoXiaoQuWuYeBiaoModel>();
            var dt = report.Select(obj => obj.Id, "Id")
                .Select(obj => obj.BianHao, "BianHao")
                .Select(obj => obj.MingCheng, "MingCheng")
                  .Select(obj => obj.ZhangHuBianHao, "ZhangHuBianHao")
                .OrderByFormat("convert({0} USING gbk) COLLATE gbk_chinese_ci", Dudu.DBServices.SortType.ASC, obj => obj.MingCheng).Execute();
            return dt.ToJsonList(StringFormatType.FirstUpper);
        }

        /// <summary>
        /// 查询房屋列表
        /// </summary>
        /// <param name="xiaoqubianhao"></param>
        /// <param name="loudonghao"></param>
        /// <param name="danyuanhao"></param>
        /// <returns></returns>
        [PramaRule("xiaoqubianhao", "小区编号(xiaoqubianhao)")]
        [PramaRule("loudonghao", "楼栋号(loudonghao)", 1, 30, false, "")]
        [PramaRule("danyuanhao", "单元号(danyuanhao)", 1, 30, false, "")]
        [ApiService("查询房屋列表", false)]
        public object FerFangWuList(string xiaoqubianhao, string loudonghao, string danyuanhao)
        {
            var report = MyType.GetReportService<Rsd.Faith.Models.InfoFangWuXinXiBiaoModel>();
            report.Select().Where(obj => obj.XiaoQuBianHao == xiaoqubianhao);

            if (!string.IsNullOrEmpty(loudonghao))
            {
                var list = loudonghao.Split(',');
                if (list.Length > 0)
                {
                    report.Where(obj => list.Contains(obj.LouDongHao));
                }

            }

            if (!string.IsNullOrEmpty(danyuanhao))
            {
                var list = danyuanhao.Split(',');
                if (list.Length > 0)
                {
                    report.Where(obj => list.Contains(obj.DanYuanHao));
                }

            }

            var dt = report.Execute();

            return dt.ConvertToBizObjects<Rsd.Faith.Models.InfoFangWuXinXiBiaoModel>();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="xiaoqubianhao"></param>
        /// <returns></returns>
        [PramaRule("xiaoqubianhao", "小区编号(xiaoqubianhao)")]
        [PramaRule("loudonghao", "楼栋号(loudonghao)", 1, 30, false, "")]
        [PramaRule("danyuanhao", "单元号(danyuanhao)", 1, 30, false, "")]
        [ApiService("小区楼栋列表", true)]
        public object GetLouDongList(string xiaoqubianhao, string loudonghao, string danyuanhao)
        {
            var report = MyType.GetReportService<Rsd.Faith.Models.InfoFangWuXinXiBiaoModel>();
            report.Count(obj => obj.BianHao, "HuShu")
                .GroupBy(obj => obj.XiaoQuBianHao, "XiaoQuBianHao")
                .GroupBy(obj => obj.LouDongHao, "LouDongHao")
                .GroupBy(obj => obj.DanYuanHao, "DanYuanHao")
                .Where(obj => obj.XiaoQuBianHao == xiaoqubianhao);

            if (!string.IsNullOrEmpty(loudonghao))
            {
                report.Where(obj => obj.LouDongHao == loudonghao);
                report.OrderBy(obj => obj.LouDongHao, Dudu.DBServices.SortType.ASC);
            }

            if (!string.IsNullOrEmpty(danyuanhao))
            {
                report.Where(obj => obj.DanYuanHao == danyuanhao);
                report.OrderBy(obj => obj.DanYuanHao, Dudu.DBServices.SortType.ASC);
            }
            var dt = report.Execute();
            return dt.ToJsonList();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="xiaoQuBianHao"></param>
        [PramaRule("xiaoqubianhao", "小区编号(xiaoqubianhao)")]
        [PramaRule("loudonghao", "楼栋号(loudonghao)", 1, 30, false, "")]
        [PramaRule("danyuanhao", "单元号(danyuanhao)", 1, 30, false, "")]
        [ApiService("小区信息和楼栋列表", true)]
        public object GetXiaoQuAndLouDongList(string xiaoQuBianHao, string louDongHao, string danYuanHao)
        {
            var xiaoqu = this.GetObject<Rsd.Faith.Models.InfoXiaoQuWuYeBiaoModel>(obj => obj.BianHao == xiaoQuBianHao);

            var list = GetLouDongList(xiaoQuBianHao, louDongHao, danYuanHao);

            return new { XiaoQu = xiaoqu, LouDongList = list };
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [PramaRule("city", "行政区市(city)", 1, 20, false, "扬中")]
        [PramaRule("zone", "片区(zone)", 1, 50, false, "")]
        [PramaRule("name", "楼盘名称(name)", 1, 200, false, "")]
        [PramaRule("address", "楼盘座落(address)", 1, 200, false, "")]
        [PramaRule("preSellNo", "预(销)售许可证号(preSellNo)", 1, 100, false, "")]
        [PramaRule("company", "开发商名称(company)", 1, 100, false, "")]
        [ApiService("查询楼盘预售信息", false)]
        public object FindLouPanYuShou(string city, string zone, string name, string address, string preSellNo, string company)
        {
            //pjtRegion
            //pjtZone: 
            //blname:
            //bladdr:
            //blsellapprno:
            //blsell: 

            //currentPage

            string url = "http://221.6.146.72:9080/estate2/olestate/search2.action";


            var _data = new JsonObject();

            if (!string.IsNullOrEmpty(city))
            {
                _data.Add("pjtRegion", city);
            }
            if (!string.IsNullOrEmpty(zone))
            {
                _data.Add("pjtZone", zone);
            }
            if (!string.IsNullOrEmpty(name))
            {
                _data.Add("blname", name);
            }
            if (!string.IsNullOrEmpty(address))
            {
                _data.Add("bladdr", address);
            }
            if (!string.IsNullOrEmpty(preSellNo))
            {
                _data.Add("blsellapprno", preSellNo);
            }
            if (!string.IsNullOrEmpty(company))
            {
                _data.Add("blsell", company);
            }
            var rs = new List<Object>();
            var currentIndex = 1;
            var paggIndexs = new List<int>();

            var html = this.HttpPost(url, _data.ToArray(), 60, "application/x-www-form-urlencoded", Encoding.GetEncoding("gb2312"), this.GetClientIp());

            rs.AddRange(this.ParseYuShouHtml(html.Data, ref paggIndexs)); 

            while (currentIndex < paggIndexs[paggIndexs.Count - 1])
            {
                currentIndex++;
                _data.Add("currentPage", currentIndex);
                paggIndexs = new List<int>();
                html = this.HttpPost(url, _data.ToArray(), 60, "application/x-www-form-urlencoded", Encoding.GetEncoding("gb2312"), this.GetClientIp());
                rs.AddRange(this.ParseYuShouHtml(html.Data, ref paggIndexs));
            }

            return rs;
        }

        //

        private object[] ParseYuShouHtml(string html, ref List<int> paggIndexs)
        {
            var rs = new List<Object>();
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(html);

            var nodeList = doc.DocumentNode.SelectNodes("/html/body/div/table");
            nodeList = nodeList[1].SelectNodes("tr/td");
            nodeList = nodeList[1].SelectNodes("table");
            nodeList = nodeList[0].SelectNodes("tr");
            nodeList = nodeList[0].SelectNodes("td");
            var pagging = nodeList[0].SelectNodes("div/a");
            nodeList = nodeList[0].SelectNodes("table/tr");

            foreach (HtmlNode item in nodeList)
            {
                var cells = item.SelectNodes("td");
                var a = cells[0].SelectSingleNode("a");
                if (a != null)
                {
                    var linkUrl = a.GetAttributeValue("href", "");
                    //estate2/olestate/queryBuildPrep.action?paramlp.blNo=1301410107&paramlp.blName=绿翠园
                    var bianhao = linkUrl.Substring("estate2/olestate/queryBuildPrep.action?paramlp.blNo=".Length + 1);
                    bianhao = bianhao.Split('&')[0];
                    rs.Add(new
                    {
                        LouPan = cells[0].InnerText.Replace("\r\n", ""),
                        BianHao = bianhao,
                        LouDongHao = cells[1].InnerText.Replace("\r\n", ""),
                        DiZhi = cells[2].InnerText.Replace("\r\n", ""),
                        DiQu = cells[3].InnerText.Replace("\r\n", ""),
                        KouShouTaoShu = cells[4].InnerText.Replace("\r\n", ""),
                        FaBuRiQi = cells[5].InnerText.Replace("\r\n", "")
                    });
                }


            }

            foreach (var item in pagging)
            {
                if (StringHelper.IsInt(item.InnerText))
                {
                    paggIndexs.Add(int.Parse(item.InnerText));
                }
            }

            return rs.ToArray();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [PramaRule("bianhao", "楼盘预售编号(bianhao)", 1, 100, true, "")]
        [PramaRule("name", "楼盘预售编号(name)", 1, 100, true, "")]
        [ApiService("查询楼盘预售明细信息", false)]
        public object GetLouDongMingXi(string bianhao, string name)
        {
            //paramlp.blNo: 2101380303
            //currentPage: 2

            var currentIndex = 1;
            var _data = new JsonObject();
            _data.Add("paramlp.blNo", bianhao);
            _data.Add("paramlp.blName", name);
            _data.Add("currentPage", currentIndex);

            var url = "http://221.6.146.72:9080/estate2/olestate/queryLpxqList.action";

            var html = this.HttpPost(url, _data.ToArray(), 60, "application/x-www-form-urlencoded", Encoding.GetEncoding("gb2312"), this.GetClientIp());
            var rs = new List<Object>();
         
            var paggIndexs = new List<int>();
            rs.AddRange(this.ParseMingXiHtml(html.Data, ref paggIndexs));

            while (currentIndex < paggIndexs[paggIndexs.Count - 1])
            {
                currentIndex++;
                _data.Add("currentPage", currentIndex);
                paggIndexs = new List<int>();
                html = this.HttpPost(url, _data.ToArray(), 60, "application/x-www-form-urlencoded", Encoding.GetEncoding("gb2312"), this.GetClientIp());
                rs.AddRange(this.ParseMingXiHtml(html.Data, ref paggIndexs));
            }

            return rs;
        }


        private object[] ParseMingXiHtml(string html, ref List<int> paggIndexs)
        {
            var rs = new List<Object>();
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(html);
            ///html/body/div/table[2]/tbody/tr[1]/td[2]/div/table[2]/tbody/tr[1]/td/table/tbody
            var nodeList = doc.DocumentNode.SelectNodes("html/body/div/table");
            nodeList = nodeList[1].SelectNodes("tr/td");
            nodeList = nodeList[1].SelectNodes("div/table");
            nodeList = nodeList[1].SelectNodes("tr/td/table"); 
            var pagging = nodeList[0].SelectNodes("tbody/tr/td/form/div/a");
            nodeList = nodeList[0].SelectNodes("tbody/tr");

            foreach (HtmlNode item in nodeList)
            {
                var cells = item.SelectNodes("td");
                if (cells.Count < 7)
                {
                    continue;
                }
                var a = cells[0].SelectSingleNode("a");
                if (a != null)
                {
                    rs.Add(new
                    {
                        DaiMa = cells[0].InnerText.Replace("\r\n", "").Replace("\t", ""),
                        LouDongHao = cells[1].InnerText.Replace("\r\n", "").Split('/')[1].Replace("幢",""),
                        LouCeng = cells[2].InnerText.Replace("\r\n", ""),
                        ShiHao = cells[3].InnerText.Replace("\r\n", ""),
                        XingZhi = cells[4].InnerText.Replace("\r\n", ""),
                        MianJi = cells[6].InnerText.Replace("\r\n", "")
                    });
                }

            }

            foreach (var item in pagging)
            {
                if (StringHelper.IsInt(item.InnerText))
                {
                    paggIndexs.Add(int.Parse(item.InnerText));
                }
            }

            return rs.ToArray();
        }
    }
}
